<template>
	<view class="page-container">
		<view class="nav-header">
			<u-icon name="arrow-left" size="22" @click="goBack"></u-icon>
			<text class="nav-title">创建账户</text>
		</view>

		<view class="form-area">
			<view class="tab-switcher">
				<view class="tab-item" :class="{ 'active': currentTab === 'phone' }" @click="switchTab('phone')">
					手机号注册
				</view>
				<view class="tab-item" :class="{ 'active': currentTab === 'email' }" @click="switchTab('email')">
					邮箱注册
				</view>
			</view>

			<!-- 手机号注册 -->
			<view v-show="currentTab === 'phone'" class="form-content">
				<u-form :model="phoneForm" ref="phoneFormRef" :rules="rules.phone">
					<u-form-item prop="phone">
						<u-input v-model="phoneForm.phone" type="number" placeholder="请输入手机号" prefixIcon="phone-fill"
							clearable></u-input>
					</u-form-item>
					<u-form-item prop="code">
						<u-input v-model="phoneForm.code" type="number" placeholder="请输入验证码" prefixIcon="email-fill"
							clearable>
							<template #suffix>
								<u-code ref="phoneCodeRef" @change="phoneCodeChange" seconds="60"></u-code>
								<u-button @tap="sendPhoneCode" :text="phoneCodeTips" type="success" size="mini"
									:disabled="isSendingPhone"></u-button>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item prop="password">
						<u-input v-model="phoneForm.password" type="password" placeholder="请输入密码" prefixIcon="lock-fill"
							clearable></u-input>
					</u-form-item>
					<u-form-item prop="nickname">
						<u-input v-model="phoneForm.nickname" placeholder="请输入昵称 (选填)" prefixIcon="account-fill"
							clearable></u-input>
					</u-form-item>
				</u-form>
			</view>

			<!-- 邮箱注册 -->
			<view v-show="currentTab === 'email'" class="form-content">
				<u-form :model="emailForm" ref="emailFormRef" :rules="rules.email">
					<u-form-item prop="email">
						<u-input v-model="emailForm.email" placeholder="请输入电子邮箱" prefixIcon="email-fill"
							clearable></u-input>
					</u-form-item>
					<u-form-item prop="code">
						<u-input v-model="emailForm.code" type="number" placeholder="请输入验证码" prefixIcon="chat-fill"
							clearable>
							<template #suffix>
								<u-code ref="emailCodeRef" @change="emailCodeChange" seconds="60"></u-code>
								<u-button @tap="sendEmailCode" :text="emailCodeTips" type="success" size="mini"
									:disabled="isSendingEmail"></u-button>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item prop="password">
						<u-input v-model="emailForm.password" type="password" placeholder="请输入密码" prefixIcon="lock-fill"
							clearable></u-input>
					</u-form-item>
					<u-form-item prop="nickname">
						<u-input v-model="emailForm.nickname" placeholder="请输入昵称 (选填)" prefixIcon="account-fill"
							clearable></u-input>
					</u-form-item>
				</u-form>
			</view>

			<view class="action-button">
				<u-button type="primary" shape="circle" @click="handleRegister">立即注册</u-button>
			</view>

			<view class="extra-links">
				<text>已有账号？</text>
				<text class="link" @click="goToLogin">立即登录</text>
			</view>
		</view>
	</view>
</template>

<script>
import uForm from '@/node_modules/uview-ui/components/u-form/u-form.vue';
import uFormItem from '@/node_modules/uview-ui/components/u-form-item/u-form-item.vue';
import uInput from '@/node_modules/uview-ui/components/u-input/u-input.vue';
import uButton from '@/node_modules/uview-ui/components/u-button/u-button.vue';
import uCode from '@/node_modules/uview-ui/components/u-code/u-code.vue';
import uIcon from '@/node_modules/uview-ui/components/u-icon/u-icon.vue';
import {
	userApi
} from '@/src/api/user.js';

export default {
	components: {
		uForm,
		uFormItem,
		uInput,
		uButton,
		uCode,
		uIcon
	},
	data() {
		return {
			currentTab: 'phone',
			phoneForm: {
				phone: '',
				code: '',
				password: '',
				nickname: ''
			},
			emailForm: {
				email: '',
				code: '',
				password: '',
				nickname: ''
			},
			phoneCodeTips: '获取验证码',
			emailCodeTips: '获取验证码',
			isSendingPhone: false,
			isSendingEmail: false,
			rules: {
				phone: {
					phone: [{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => uni.$u.test.mobile(value),
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}],
					code: {
						required: true,
						message: '请输入验证码',
						trigger: ['blur', 'change']
					},
					password: {
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
				},
				email: {
					email: [{
						required: true,
						message: '请输入邮箱',
						trigger: ['blur', 'change']
					}, {
						type: 'email',
						message: '邮箱格式不正确',
						trigger: ['blur', 'change']
					}],
					code: {
						required: true,
						message: '请输入验证码',
						trigger: ['blur', 'change']
					},
					password: {
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
				}
			}
		}
	},
	methods: {
		switchTab(tab) {
			this.currentTab = tab;
		},
		goBack() {
			uni.navigateBack();
		},
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/index'
			});
		},
		handleRegister() {
			if (this.currentTab === 'phone') {
				this.phoneRegister();
			} else {
				this.emailRegister();
			}
		},
		phoneRegister() {
			this.$refs.phoneFormRef.validate().then(valid => {
				if (valid) {
					userApi.registerBySms(this.phoneForm).then(res => {
						this.handleSuccess(res);
					}).catch(err => {
						this.handleError(err);
					})
				}
			})
		},
		emailRegister() {
			this.$refs.emailFormRef.validate().then(valid => {
				if (valid) {
					userApi.register(this.emailForm).then(res => {
						this.handleSuccess(res);
					}).catch(err => {
						this.handleError(err);
					});
				}
			});
		},
		sendPhoneCode() {
			this.$refs.phoneFormRef.validateField('phone', (errors) => {
				if (errors.length) return;
				if (this.isSendingPhone) return;

				this.isSendingPhone = true;
				userApi.sendSmsCode(this.phoneForm.phone, 'register').then(res => {
					uni.showToast({ title: '验证码已发送', icon: 'success' });
					this.$refs.phoneCodeRef.start();
				}).catch(err => {
					this.isSendingPhone = false;
					this.handleError(err, '验证码发送失败');
				});
			});
		},
		sendEmailCode() {
			this.$refs.emailFormRef.validateField('email', (errors) => {
				if (errors.length) return;
				if (this.isSendingEmail) return;

				this.isSendingEmail = true;
				userApi.sendEmailCode(this.emailForm.email, 'register').then(res => {
					uni.showToast({ title: '验证码已发送', icon: 'success' });
					this.$refs.emailCodeRef.start();
				}).catch(err => {
					this.isSendingEmail = false;
					this.handleError(err, '验证码发送失败');
				});
			});
		},
		phoneCodeChange(text) {
			this.phoneCodeTips = text;
		},
		emailCodeChange(text) {
			this.emailCodeTips = text;
		},
		handleSuccess(res) {
			if (res && res.code === 200) {
				uni.showToast({ title: '注册成功！', icon: 'success' });
				setTimeout(() => this.goToLogin(), 1500);
			} else {
				uni.showToast({ title: res.message || '操作失败', icon: 'none' });
			}
		},
		handleError(err, defaultMsg = '请求失败') {
			uni.showToast({ title: err.message || defaultMsg, icon: 'none' });
		}
	},
	onReady() {
		this.$refs.phoneFormRef.setRules(this.rules.phone);
		this.$refs.emailFormRef.setRules(this.rules.email);
	}
}
</script>

<style lang="scss">
.page-container {
	padding: 0 40rpx 80rpx;
	background-color: $page-bg-color;
	min-height: 100vh;
	box-sizing: border-box;
}

.nav-header {
	display: flex;
	align-items: center;
	padding: 90rpx 0 50rpx;

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: $text-primary-color;
		transform: translateX(-22rpx);
	}
}

.form-area {
	background-color: $card-bg-color;
	padding: 60rpx 50rpx;
	border-radius: 24rpx;
	box-shadow: $shadow;
}

.tab-switcher {
	display: flex;
	margin-bottom: 60rpx;

	.tab-item {
		flex: 1;
		text-align: center;
		padding-bottom: 20rpx;
		font-size: 34rpx;
		color: $text-secondary-color;
		position: relative;
		transition: color 0.3s;

		&.active {
			color: $theme-color;
			font-weight: bold;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 120rpx;
				height: 8rpx;
				background-color: $theme-color;
				border-radius: 4rpx;
			}
		}
	}
}

.form-content {
	/deep/ .u-form-item {
		padding: 10rpx 0;
	}

	/deep/ .u-input {
		background-color: $page-bg-color;
		padding: 12rpx 24rpx !important;
		border-radius: 16rpx;
	}
}

.action-button {
	margin-top: 80rpx;

	/deep/ .u-button--primary {
		background-color: $theme-color;
		border-color: $theme-color;
		box-shadow: 0 8rpx 16rpx rgba(217, 109, 0, 0.2);
	}
}

.extra-links {
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 26rpx;
	color: $text-secondary-color;
	margin-top: 50rpx;

	.link {
		color: $theme-color;
		margin-left: 10rpx;
		font-weight: bold;
	}
}
</style>